/*
 * @Descripttion: 
 * @version: 
 * @Author: cyj
 * @Date: 2023-03-09 11:31:20
 */
//下载音乐的插件
//检查歌曲和获取歌曲url
//实现下载音频
import axios from 'axios'
import { getSongUrl, checkMusic } from '@/api/playmusic/playmusic.js'
import { ElMessage } from 'element-plus'
let dowmMuiscURL = ''
async function getSong(song) {
    let res = await checkMusic(song.id)
    if (res.data.success == true) {  //说明歌曲可用
        let res1 = await getSongUrl(song.id)
        if (res1.data.code === 200)
            //保存音频地址
            dowmMuiscURL = res1.data.data[0].url
    }
}


//下载音乐
async function downloadmusic(song) {
    //检查歌曲和获取歌曲url
    await getSong(song)  //确保song地址已经有
    axios({
        method: 'GET',
        url: dowmMuiscURL,  //请求下载音频的地址
        responseType: 'blob',  //返回的是blob数据流
        timeout: 30000,
    }).then(res => {
        let url = window.URL.createObjectURL(res.data) //生成链接地址 —— 请求下载数据的地址
        const ele = document.createElement('a')  //创建一个a标签
        ele.setAttribute('href', url)  //把url给到a链接url
        ele.setAttribute('download', `${song.name}-${song.ar[0].name}`)
        document.body.appendChild(ele)
        ele.click()  //自动点击
        window.URL.revokeObjectURL(url)  //移除链接对象
        document.body.removeChild(ele)   //移除节点
    }).catch(err => {
        ElMessage({
            message: '暂无版权，无法下载',
            type: 'warning',
            center: true
        })
    })
}
export default downloadmusic